package com.liberty.servlet.async;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
@RequestMapping("async")
public class AsyncTestController {

	long wait = 10 *1000;
	
	long chat = 30 *1000;
	
	Map<String,DeferredResult<Map<String, String>>> resultMap = new HashMap<>();
	
	@Autowired
	private AsyncHandler asyncHandler;
	
	@GetMapping("long/poll")
	public DeferredResult<Map<String, String>> longpoll(String id) {
		System.out.println(
				"this is longpoll:" + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
		DeferredResult<Map<String, String>> deferredResult = new DeferredResult<>(wait);
		deferredResult.setResultHandler(asyncHandler);
		resultMap.put(id, deferredResult);
		
		deferredResult.onTimeout(new Runnable() {
			
			@Override
			public void run() {
				System.out.println(
						"this is longpoll timeout:" + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
				Map<String, String> map = new HashMap<>();
				map.put("msg", "id: "+id+" timeout");
				deferredResult.setResult(map);
			}
		});
		
		deferredResult.onCompletion(new Runnable() {
			
			@Override
			public void run() {
				System.out.println(
						"this is longpoll complete:" + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
				resultMap.remove(id);
			}
		});
		
//		try {
//			Thread.sleep(wait-1000);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		Map<String, String> map = new HashMap<>();
//		map.put("msg", "id:"+id);
//		deferredResult.setResult(map);
		return deferredResult;
	}
	
	@GetMapping("notify")
	public Map<String, String> notify(String id, String msg) {
		Map<String, String> map = new HashMap<>();
		map.put("msg", "id:"+id+ " " +msg);
		resultMap.get(id).setResult(map);
		return map;
	}
	
	
	@GetMapping("test")
	public Map<String, String> test() {
		try {
			Thread.sleep(wait);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map<String, String> map = new HashMap<>();
		return map;
	}
}
